package com.qb.libcommon.utils;

import android.app.Application;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;

/**
 * @author wuqiubin
 * @date 2023/1/16
 * @Describe
 */
public class ApplicationUtils {
    private static Application sApplication;

    public static void init(Application app) {
        if (sApplication == null) {
            if (app == null) {
                sApplication = getApplicationByReflect();
            } else {
                sApplication = app;
            }
        } else if (app != null && app.getClass() != sApplication.getClass()) {
            sApplication = app;
        }

    }
    /**
     * Return the Application object.
     * <p>Main process get app by UtilsFileProvider,
     * and other process get app by reflect.</p>
     *
     * @return the Application object
     */
    public static Application getApplication() {
        if (sApplication != null) return sApplication;
        init(getApplicationByReflect());
        if (sApplication == null) throw new NullPointerException("reflect failed.");
        return sApplication;
    }

    private static Application getApplicationByReflect() {
        try {
            Class<?> activityThread = Class.forName("android.app.ActivityThread");
            Object thread = activityThread.getMethod("currentActivityThread").invoke((Object)null);
            Object app = activityThread.getMethod("getApplication").invoke(thread);
            if (app == null) {
                throw new NullPointerException("请先初始化Application");
            }

            return (Application)app;
        } catch (NoSuchMethodException var3) {
            var3.printStackTrace();
        } catch (IllegalAccessException var4) {
            var4.printStackTrace();
        } catch (InvocationTargetException var5) {
            var5.printStackTrace();
        } catch (ClassNotFoundException var6) {
            var6.printStackTrace();
        }

        throw new NullPointerException("请先初始化Application");
    }
}
